package view.dialog;

import tool.DisableEditTableModel;

import javax.swing.*;

import bean.Department;
import dao.DepartmentDAO;
import dao.EmployeeDAO;

import java.awt.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Vector;

public class DepartmentDialog extends JDialog {
    private static final long serialVersionUID = -5657763233883250271L;
    private DepartmentDAO departmentDAO;
    private EmployeeDAO employeeDAO;
    private Dimension dimension;
    private JPanel contentPane;
    private JScrollPane scrollPane;
    private JTable table;
    private DisableEditTableModel tableModel;
    private Vector<String> columnNames;
    private JPanel rightPanel;
    private JButton editDepartmentButton;
    private JButton addDepartmentButton;
    private JButton deleteDepartmentButton;
    private JPanel panel1, panel2, panel3, panel4, panel5, panel6;
    private JTextField departmentIdTextField;
    private JTextField departmentNameTextField;
    private JButton refreshButton;
    private JButton submitButton;

    public DepartmentDialog(Connection conn) throws SQLException, ClassNotFoundException {
        departmentDAO = new DepartmentDAO(conn);
        employeeDAO = new EmployeeDAO(conn);
        setSize(450, 300);
        setTitle("管理部门");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setModalityType(ModalityType.APPLICATION_MODAL);
        dimension = new Dimension(83, 22);
        contentPane = (JPanel) getContentPane();
        contentPane.setLayout(new BorderLayout());
        scrollPane = new JScrollPane();
        table = new JTable();
        tableModel = new DisableEditTableModel();
        columnNames = new Vector<>();
        columnNames.addElement("部门编号");
        columnNames.addElement("部门名称");
        tableModel.setDataVector(rowsData(), columnNames);
        table.setModel(tableModel);
        scrollPane.setViewportView(table);
        contentPane.add(scrollPane, BorderLayout.CENTER);
        contentPane.add(new JPanel(new GridLayout(6, 1)), BorderLayout.EAST);
        rightPanel = (JPanel) contentPane.getComponent(1);
        rightPanel.add(new JPanel());
        panel1 = (JPanel) rightPanel.getComponent(0);
        editDepartmentButton = new JButton("编辑部门");
        editDepartmentButton.addActionListener(actionEvent -> {
            int length = table.getSelectedRows().length;
            if (length == 1) {
                int departmentId = (int) tableModel.getValueAt(table.getSelectedRow(), 0);
                try {
                    Department department = departmentDAO.selectById(departmentId);
                    departmentIdTextField.setText(String.valueOf(department.getDepartmentId()));
                    departmentNameTextField.setText(department.getDepartmentName());
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        panel1.add(editDepartmentButton);
        rightPanel.add(new JPanel());
        panel2 = (JPanel) rightPanel.getComponent(1);
        addDepartmentButton = new JButton("添加部门");
        addDepartmentButton.addActionListener(actionEvent -> {
            table.clearSelection();
            departmentIdTextField.setText(null);
            departmentNameTextField.setText(null);
        });
        panel2.add(addDepartmentButton);
        rightPanel.add(new JPanel());
        panel3 = (JPanel) rightPanel.getComponent(2);
        deleteDepartmentButton = new JButton("删除部门");
        deleteDepartmentButton.addActionListener(actionEvent -> {
            int[] rows = table.getSelectedRows();
            if (rows.length > 0) {
                for (int rowIndex = rows.length - 1; rowIndex > -1; rowIndex--) {
                    int departmentId = (int) tableModel.getValueAt(rows[rowIndex], 0);
                    try {
                        int count = employeeDAO.selectIdCountByDepartmentId(departmentId);
                        if (count == 0) {
                            departmentDAO.delete(departmentId);
                            tableModel.setDataVector(rowsData(), columnNames);
                        } else if (count == -1) {
                            JOptionPane.showMessageDialog(null, "部门编号不能为0");
                            break;
                        } else {
                            JOptionPane.showMessageDialog(null, "部门编号：" + departmentId + "包含有员工");
                            break;
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        panel3.add(deleteDepartmentButton);
        rightPanel.add(new JPanel());
        panel4 = (JPanel) rightPanel.getComponent(3);
        panel4.add(new JLabel("部门编号"));
        departmentIdTextField = new JTextField();
        departmentIdTextField.setPreferredSize(dimension);
        departmentIdTextField.setEnabled(false);
        panel4.add(departmentIdTextField);
        rightPanel.add(new JPanel());
        panel5 = (JPanel) rightPanel.getComponent(4);
        panel5.add(new JLabel("部门名称"));
        departmentNameTextField = new JTextField();
        departmentNameTextField.setPreferredSize(dimension);
        panel5.add(departmentNameTextField);
        rightPanel.add(new JPanel());
        panel6 = (JPanel) rightPanel.getComponent(5);
        refreshButton = new JButton("刷新");
        refreshButton.addActionListener(actionEvent -> {
            try {
                tableModel.setDataVector(rowsData(), columnNames);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
        panel6.add(refreshButton);
        submitButton = new JButton("提交");
        submitButton.addActionListener(actionEvent -> {
            String departmentName = departmentNameTextField.getText();
            boolean state;
            if (Objects.nonNull(departmentName) && departmentName.length() > 0) {
                String departmentIdText = departmentIdTextField.getText();
                try {
                    if (Objects.nonNull(departmentDAO.selectByName(departmentName))) {
                        JOptionPane.showMessageDialog(null, "指定部门名称已存在，请重新编辑部门名称");
                        departmentNameTextField.requestFocusInWindow();
                        departmentNameTextField.selectAll();
                    } else {
                        if (Objects.nonNull(departmentIdText) && departmentIdText.length() > 0) {
                            // 编辑部门
                            int departmentId = Integer.parseInt(departmentIdText);
                            state = departmentDAO.update(departmentId, departmentName);
                            if (state) {
                                JOptionPane.showMessageDialog(null, "编辑部门成功");
                                departmentIdTextField.setText(null);
                                departmentNameTextField.setText(null);
                            } else {
                                JOptionPane.showMessageDialog(null, "编辑部门失败");
                            }
                        } else {
                            // 添加部门
                            state = departmentDAO.insert(departmentName);
                            if (state) {
                                JOptionPane.showMessageDialog(null, "添加部门成功");
                                departmentIdTextField.setText(null);
                                departmentNameTextField.setText(null);
                            } else {
                                JOptionPane.showMessageDialog(null, "添加部门失败");
                            }
                        }
                        tableModel.setDataVector(rowsData(), columnNames);
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            } else {
                JOptionPane.showMessageDialog(null, "部门名称不能为空");
            }
        });
        panel6.add(submitButton);
    }

    private Vector<Vector<Object>> rowsData() throws SQLException {
        Vector<Vector<Object>> rowsData = new Vector<>();
        Vector<Department> departments = departmentDAO.selectAll();
        for (Department department : departments) {
            Vector<Object> rowData = new Vector<>();
            rowData.addElement(department.getDepartmentId());
            rowData.addElement(department.getDepartmentName());
            rowsData.addElement(rowData);
        }
        return rowsData;
    }
}
